package com.hankol.message.fragment

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseFragment
import com.baselibrary.bean.BottomDialogBean
import com.baselibrary.extension.checkNotNull
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.DoubleClickHelper
import com.baselibrary.utils.IntentKey
import com.baselibrary.utils.PopUtils
import com.baselibrary.utils.SpUtils
import com.baselibrary.utils.StatusBarUtil.setStatusBarDarkTheme
import com.baselibrary.utils.StatusBarUtil.setStatusBarHeight
import com.hankol.message.R
import com.hankol.message.databinding.FragmentHomeMessageBinding
import com.hankol.message.view.HomeMsgHeadView
import com.hankol.message.viewmodel.HomeMessageViewModel
import io.rong.imkit.IMCenter
import io.rong.imkit.RongIM
import io.rong.imkit.config.ConversationListBehaviorListener
import io.rong.imkit.conversationlist.model.BaseUiConversation
import io.rong.imlib.model.Conversation
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**首页tab-消息
 * @author: merbng
 * @time: 2022/3/24 10:05
 * @description:
 */
class HomeMessageFragment : BaseFragment() {
    private var mBinding: FragmentHomeMessageBinding? = null
    private lateinit var viewModel: HomeMessageViewModel
    private var mImFragment: MyConversationListFragment? = null
    private lateinit var mMesHeadView: HomeMsgHeadView

    companion object {

        fun newInstance(): HomeMessageFragment {
            val fragment = HomeMessageFragment()
            return fragment
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_home_message
    }

    override fun init() {
        SensorsDataManager.instance.onCreateTime()
        mBinding = getDataBinding<FragmentHomeMessageBinding>()
        viewModel = getFragmentViewModelProvider(this).get(HomeMessageViewModel::class.java)
        setStatusBarHeight(mBinding!!.root, activity)
        setStatusBarDarkTheme(activity, true)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        initConverstation()

        viewModel.unReadCntLD.observe(this, Observer {
            if (it.checkNotNull()) {
                mMesHeadView.setTopCnt(it)
            }
        })
        viewModel.sysMsgLD.observe(this, Observer {
            it?.let {
                mMesHeadView.setSystemListData(it)
            }
        })
    }

    fun requestData() {
        viewModel.reqUnReadCnt()
        viewModel.reqGetSysMsgList()
    }

    private fun initConverstation() {
        mImFragment = viewModel.initConversation(childFragmentManager)
        mMesHeadView = HomeMsgHeadView(requireContext(), requireActivity())
        mImFragment?.addHeaderView(mMesHeadView)
        setRongYunListener()

    }

    private fun setRongYunListener() {
        RongIM.setConversationListBehaviorListener(object : ConversationListBehaviorListener {
            override fun onConversationLongClick(p0: Context?, p1: View?, uiConversation: BaseUiConversation): Boolean {
                val dataList = mutableListOf<BottomDialogBean>()
                dataList.add(BottomDialogBean("删除"))
                dataList.add(BottomDialogBean(if (uiConversation.mCore.isTop()) "取消置顶" else "置顶"))
                PopUtils.showBottomDialog(activity!!, "", dataList, object : PopUtils.IitemCallBack {
                    override fun onItemClick(pos: Int) {
                        if (pos == 0) {
                            IMCenter.getInstance().removeConversation(uiConversation.mCore.getConversationType(), uiConversation.mCore.getTargetId(), null)
                        } else if (pos == 1) {
                            IMCenter.getInstance().setConversationToTop(uiConversation.mCore.getConversationType(), uiConversation.mCore.getTargetId(), !uiConversation.mCore.isTop(), false, null)
                        }
                    }
                }).show()
                return true
            }

            override fun onConversationClick(p0: Context?, p1: View?, p2: BaseUiConversation?): Boolean {
                SpUtils.getInstance().savePagePos4Chat("消息列表")
                return false
            }

            /**
             * 会话头像点击监听
             *
             * @param context          上下文。
             * @param conversationType 会话类型。
             * @param targetId         被点击的用户id。
             * @return true 拦截事件, false 执行融云 SDK 内部默认处理逻辑
             */
            override fun onConversationPortraitClick(context: Context, conversationType: Conversation.ConversationType, targetId: String): Boolean {
                return false
            }

            /**
             * 会话头像长按监听
             *
             * @param context          上下文。
             * @param conversationType 会话类型。
             * @param targetId         被点击的用户id。
             * @return true 拦截事件, false 执行融云 SDK 内部默认处理逻辑
             */
            override fun onConversationPortraitLongClick(context: Context, conversationType: Conversation.ConversationType, targetId: String): Boolean {
                return false
            }
        })
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_mei_qia_have_new_msg) { //有新消息
            mMesHeadView.getMeiQiaNoReadCnt(false)
            mMesHeadView.setLastMessage()
        } else if (messageBus.codeType == MessageBus.msgid_refresh_chat_list) {
            //刷新
            requestData()
        } else if (messageBus.codeType == MessageBus.msgid_exit_or_logout) {
            //刷新
            mMesHeadView.setLastMessage()
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }

    private var hidden: Boolean = false
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        this.hidden = hidden
        if (!hidden) {
            //获取页面开始时间
            SensorsDataManager.instance.onCreateTime()
            //界面重新显示
            requestData()
        } else {
            SensorsDataManager.instance.onDestroyTime()
            if (SensorsDataManager.instance.getBrowseTime() != 0L) {
                SensorsDataManager.instance.brookPageView("消息中心")
            }
        }
    }

    override fun onResume() {
        super.onResume()
        //修改密码 跳转到登录界面，点击 返回 会回到 我的界面 判断游客模式 跳到 首页
        if (SpUtils.getInstance().loadUserBean == null || SpUtils.getInstance().loadUserBean!!.data.userRank == 99) { //游客模式
            return
        }
        if (!hidden) {
            requestData()
        }
    }

    override fun onPause() {
        super.onPause()
        //获取页面结束时间
        SensorsDataManager.instance.onDestroyTime()
        if (SensorsDataManager.instance.getBrowseTime() != 0L) {
            SensorsDataManager.instance.brookPageView("消息中心")
        }
    }
}